<!DOCTYPE html>
<html lang="zh-Hans">
<head>

    <!--[if lt IE 9]>
        <style>body {display: none; background: none !important} </style>
        <meta http-equiv="Refresh" Content="0; url=//outdatedbrowser.com/" />
    <![endif]-->

<meta charset="utf-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge, chrome=1" />
<meta name="viewport" content="width=device-width, initial-scale=1, maximum-scale=1, user-scalable=no">
<meta name="format-detection" content="telephone=no" />
<meta name="author" content="王诗翔" />



<meta name="description" content="内容  处理信号 以后台模式运行脚本 禁止挂起 作业控制 修改脚本优先级 脚本执行自动化">
<meta name="keywords" content="shell笔记,linux">
<meta property="og:type" content="article">
<meta property="og:title" content="控制脚本">
<meta property="og:url" content="https://shixiangwang.github.io/2017/09/04/control_shell/index.html">
<meta property="og:site_name" content="Cloudberry">
<meta property="og:description" content="内容  处理信号 以后台模式运行脚本 禁止挂起 作业控制 修改脚本优先级 脚本执行自动化">
<meta property="og:locale" content="zh-Hans">
<meta property="og:updated_time" content="2018-01-27T04:08:26.410Z">
<meta name="twitter:card" content="summary">
<meta name="twitter:title" content="控制脚本">
<meta name="twitter:description" content="内容  处理信号 以后台模式运行脚本 禁止挂起 作业控制 修改脚本优先级 脚本执行自动化">

<link rel="apple-touch-icon" href= "/apple-touch-icon.png">


    <link rel="alternate" href="/atom.xml" title="Cloudberry" type="application/atom+xml">



    <link rel="shortcut icon" href="/favicon.png">



    <link href="//cdn.bootcss.com/animate.css/3.5.1/animate.min.css" rel="stylesheet">



    <link href="//cdn.bootcss.com/fancybox/2.1.5/jquery.fancybox.min.css" rel="stylesheet">



    <script src="//cdn.bootcss.com/pace/1.0.2/pace.min.js"></script>
    <link href="//cdn.bootcss.com/pace/1.0.2/themes/blue/pace-theme-minimal.css" rel="stylesheet">


<link rel="stylesheet" href="../../../../css/style.css">



<link href="//cdn.bootcss.com/font-awesome/4.6.3/css/font-awesome.min.css" rel="stylesheet">


<title>控制脚本 | Cloudberry</title>

<script src="//cdn.bootcss.com/jquery/2.2.4/jquery.min.js"></script>
<script src="//cdn.bootcss.com/clipboard.js/1.5.10/clipboard.min.js"></script>

<script>
    var yiliaConfig = {
        fancybox: true,
        animate: true,
        isHome: false,
        isPost: true,
        isArchive: false,
        isTag: false,
        isCategory: false,
        fancybox_js: "//cdn.bootcss.com/fancybox/2.1.5/jquery.fancybox.min.js",
        scrollreveal: "//cdn.bootcss.com/scrollReveal.js/3.1.4/scrollreveal.min.js",
        search: true
    }
</script>


    <script>
        yiliaConfig.jquery_ui = [true, "//cdn.bootcss.com/jqueryui/1.10.4/jquery-ui.min.js", "//cdn.bootcss.com/jqueryui/1.10.4/css/jquery-ui.min.css"];
    </script>



    <script> yiliaConfig.rootUrl = "\/";</script>






</head>
<body>
  <div id="container">
    <div class="left-col">
    <div class="overlay"></div>
<div class="intrude-less">
    <header id="header" class="inner">
        <a href="/" class="profilepic">
            <img src="/img/avatar.png" class="animated zoomIn">
        </a>
        <hgroup>
          <h1 class="header-author"><a href="/">王诗翔</a></h1>
        </hgroup>

        
        <p class="header-subtitle">A site for writing life</p>
        

        
            <form id="search-form">
            <input type="text" id="local-search-input" name="q" placeholder="search..." class="search form-control" autocomplete="off" autocorrect="off" searchonload="false" />
            <i class="fa fa-times" onclick="resetSearch()"></i>
            </form>
            <div id="local-search-result"></div>
            <p class='no-result'>No results found <i class='fa fa-spinner fa-pulse'></i></p>
        


        
            <div id="switch-btn" class="switch-btn">
                <div class="icon">
                    <div class="icon-ctn">
                        <div class="icon-wrap icon-house" data-idx="0">
                            <div class="birdhouse"></div>
                            <div class="birdhouse_holes"></div>
                        </div>
                        <div class="icon-wrap icon-ribbon hide" data-idx="1">
                            <div class="ribbon"></div>
                        </div>
                        
                        <div class="icon-wrap icon-link hide" data-idx="2">
                            <div class="loopback_l"></div>
                            <div class="loopback_r"></div>
                        </div>
                        
                        
                        <div class="icon-wrap icon-me hide" data-idx="3">
                            <div class="user"></div>
                            <div class="shoulder"></div>
                        </div>
                        
                    </div>
                    
                </div>
                <div class="tips-box hide">
                    <div class="tips-arrow"></div>
                    <ul class="tips-inner">
                        <li>菜单</li>
                        <li>标签</li>
                        
                        <li>友情链接</li>
                        
                        
                        <li>关于我</li>
                        
                    </ul>
                </div>
            </div>
        

        <div id="switch-area" class="switch-area">
            <div class="switch-wrap">
                <section class="switch-part switch-part1">
                    <nav class="header-menu">
                        <ul>
                        
                            <li><a href="../../../../index.html">主页</a></li>
                        
                            <li><a href="../../../../archives/">所有文章</a></li>
                        
                            <li><a href="../../../../tags/">标签云</a></li>
                        
                            <li><a href="../../../../about/">关于我</a></li>
                        
                        </ul>
                    </nav>
                    <nav class="header-nav">
                        <ul class="social">
                            
                                <a class="fa Email" href="mailto:w_shixiang@163.com" title="Email"></a>
                            
                                <a class="fa GitHub" href="https://github.com/ShixiangWang" title="GitHub"></a>
                            
                                <a class="fa RSS" href="../../../../atom.xml" title="RSS"></a>
                            
                                <a class="fa 知乎" href="https://www.zhihu.com/people/wang-shi-xiang-65/activities" title="知乎"></a>
                            
                                <a class="fa 简书" href="https://www.jianshu.com/u/b6608e27dc74" title="简书"></a>
                            
                                <a class="fa Twitter" href="https://twitter.com/WangShxiang" title="Twitter"></a>
                            
                        </ul>
                    </nav>
                </section>
                
                
                <section class="switch-part switch-part2">
                    <div class="widget tagcloud" id="js-tagcloud">
                        <ul class="tag-list"><li class="tag-list-item"><a class="tag-list-link" href="../../../../tags/Gist/">Gist</a></li><li class="tag-list-item"><a class="tag-list-link" href="../../../../tags/Linux-shell/">Linux shell</a></li><li class="tag-list-item"><a class="tag-list-link" href="../../../../tags/OOP/">OOP</a></li><li class="tag-list-item"><a class="tag-list-link" href="../../../../tags/R/">R</a></li><li class="tag-list-item"><a class="tag-list-link" href="../../../../tags/Rmarkdown/">Rmarkdown</a></li><li class="tag-list-item"><a class="tag-list-link" href="../../../../tags/Rmd/">Rmd</a></li><li class="tag-list-item"><a class="tag-list-link" href="../../../../tags/Rstudio/">Rstudio</a></li><li class="tag-list-item"><a class="tag-list-link" href="../../../../tags/bash-shell/">bash shell</a></li><li class="tag-list-item"><a class="tag-list-link" href="../../../../tags/fasta/">fasta</a></li><li class="tag-list-item"><a class="tag-list-link" href="../../../../tags/git/">git</a></li><li class="tag-list-item"><a class="tag-list-link" href="../../../../tags/github/">github</a></li><li class="tag-list-item"><a class="tag-list-link" href="../../../../tags/lapply/">lapply</a></li><li class="tag-list-item"><a class="tag-list-link" href="../../../../tags/linux/">linux</a></li><li class="tag-list-item"><a class="tag-list-link" href="../../../../tags/markdown/">markdown</a></li><li class="tag-list-item"><a class="tag-list-link" href="../../../../tags/md/">md</a></li><li class="tag-list-item"><a class="tag-list-link" href="../../../../tags/python/">python</a></li><li class="tag-list-item"><a class="tag-list-link" href="../../../../tags/sapply/">sapply</a></li><li class="tag-list-item"><a class="tag-list-link" href="../../../../tags/sed/">sed</a></li><li class="tag-list-item"><a class="tag-list-link" href="../../../../tags/shell笔记/">shell笔记</a></li><li class="tag-list-item"><a class="tag-list-link" href="../../../../tags/survival/">survival</a></li><li class="tag-list-item"><a class="tag-list-link" href="../../../../tags/survminer/">survminer</a></li><li class="tag-list-item"><a class="tag-list-link" href="../../../../tags/vapply/">vapply</a></li><li class="tag-list-item"><a class="tag-list-link" href="../../../../tags/写作/">写作</a></li><li class="tag-list-item"><a class="tag-list-link" href="../../../../tags/数据处理/">数据处理</a></li><li class="tag-list-item"><a class="tag-list-link" href="../../../../tags/文本处理/">文本处理</a></li><li class="tag-list-item"><a class="tag-list-link" href="../../../../tags/生存分析/">生存分析</a></li><li class="tag-list-item"><a class="tag-list-link" href="../../../../tags/生物信息学/">生物信息学</a></li><li class="tag-list-item"><a class="tag-list-link" href="../../../../tags/类/">类</a></li><li class="tag-list-item"><a class="tag-list-link" href="../../../../tags/迭代计算/">迭代计算</a></li></ul>
                    </div>
                </section>
                
                
                
                <section class="switch-part switch-part3">
                    <div id="js-friends">
                    
                      <a class="main-nav-link switch-friends-link" href="http://www.ruanyifeng.com/blog/archives.html">阮一峰的网络日志</a>
                    
                      <a class="main-nav-link switch-friends-link" href="http://blog.fens.me/series-r/">R的极客理想系列</a>
                    
                      <a class="main-nav-link switch-friends-link" href="https://yihui.name/">谢益辉</a>
                    
                      <a class="main-nav-link switch-friends-link" href="http://www.huangshujia.me/">解螺旋的矿工</a>
                    
                      <a class="main-nav-link switch-friends-link" href="https://github.com/GuangchuangYu">GuangchuangYu</a>
                    
                      <a class="main-nav-link switch-friends-link" href="https://vip.biotrainee.com/">生信技能树</a>
                    
                    </div>
                </section>
                

                
                
                <section class="switch-part switch-part4">
                
                    <div id="js-aboutme">人该是自己生活的主宰，而不是别人手中的行货</div>
                </section>
                
            </div>
        </div>
    </header>                
</div>
    </div>
    <div class="mid-col">
      <nav id="mobile-nav">
      <div class="overlay">
          <div class="slider-trigger"></div>
          <h1 class="header-author js-mobile-header hide"><a href="/" title="回到主页">王诗翔</a></h1>
      </div>
    <div class="intrude-less">
        <header id="header" class="inner">
            <a href="/" class="profilepic">
                <img src="/img/avatar.png" class="animated zoomIn">
            </a>
            <hgroup>
              <h1 class="header-author"><a href="/" title="回到主页">王诗翔</a></h1>
            </hgroup>
            
            <p class="header-subtitle">A site for writing life</p>
            
            <nav class="header-menu">
                <ul>
                
                    <li><a href="../../../../index.html">主页</a></li>
                
                    <li><a href="../../../../archives/">所有文章</a></li>
                
                    <li><a href="../../../../tags/">标签云</a></li>
                
                    <li><a href="../../../../about/">关于我</a></li>
                
                <div class="clearfix"></div>
                </ul>
            </nav>
            <nav class="header-nav">
                        <ul class="social">
                            
                                <a class="fa Email" target="_blank" href="mailto:w_shixiang@163.com" title="Email"></a>
                            
                                <a class="fa GitHub" target="_blank" href="https://github.com/ShixiangWang" title="GitHub"></a>
                            
                                <a class="fa RSS" target="_blank" href="../../../../atom.xml" title="RSS"></a>
                            
                                <a class="fa 知乎" target="_blank" href="https://www.zhihu.com/people/wang-shi-xiang-65/activities" title="知乎"></a>
                            
                                <a class="fa 简书" target="_blank" href="https://www.jianshu.com/u/b6608e27dc74" title="简书"></a>
                            
                                <a class="fa Twitter" target="_blank" href="https://twitter.com/WangShxiang" title="Twitter"></a>
                            
                        </ul>
            </nav>
        </header>                
    </div>
    <link class="menu-list" tags="标签" friends="友情链接" about="关于我"/>
</nav>
      <div class="body-wrap"><article id="post-control_shell" class="article article-type-post" itemscope itemprop="blogPost">
  
    <div class="article-meta">
      <a href="" class="article-date">
      <time datetime="2017-09-03T16:00:00.000Z" itemprop="datePublished">2017-09-04</time>
</a>


    </div>
  
  <div class="article-inner">
    
      <input type="hidden" class="isFancy" />
    
    
      <header class="article-header">
        
  
    <h1 class="article-title" itemprop="name">
      控制脚本
    </h1>
  

      </header>
      
      <div class="article-info article-info-post">
        
    <div class="article-category tagcloud">
    <a class="article-category-link" href="../../../../categories/Linux杂烩/">Linux杂烩</a><a class="article-category-link" href="../../../../categories/Linux杂烩/shell编程/">shell编程</a>
    </div>


        
    <div class="article-tag tagcloud">
        <ul class="article-tag-list"><li class="article-tag-list-item"><a class="article-tag-list-link" href="../../../../tags/linux/">linux</a></li><li class="article-tag-list-item"><a class="article-tag-list-link" href="../../../../tags/shell笔记/">shell笔记</a></li></ul>
    </div>

        <div class="clearfix"></div>
      </div>
      
    
    <div class="article-entry" itemprop="articleBody">
      
          
        <blockquote>
<p><strong>内容</strong></p>
<ul>
<li>处理信号</li>
<li>以后台模式运行脚本</li>
<li>禁止挂起</li>
<li>作业控制</li>
<li>修改脚本优先级</li>
<li>脚本执行自动化</li>
</ul>
</blockquote>
<a id="more"></a>
<p>除了在命令行界面世界运行脚本，还存在一些方法：<strong>向脚本发送信号、修改脚本的优先级以及在脚本运行时切换到运行模式</strong>。</p>
<p>下面逐一讲述。</p>
<h2 id="处理信号"><a href="#处理信号" class="headerlink" title="处理信号"></a>处理信号</h2><p>Linux利用信号与运行在系统中的进程进行通信。我们可以通过对脚本编程，使其在收到特定信号时执行某些命令，从而实现对脚本运行的控制。</p>
<h3 id="Linux信号"><a href="#Linux信号" class="headerlink" title="Linux信号"></a>Linux信号</h3><p>Linux和应用程序可以生成超过30个信号。下面列出最常见的系统信号。</p>
<table>
<thead>
<tr>
<th style="text-align:center">信号</th>
<th style="text-align:center">值</th>
<th style="text-align:center">描述</th>
</tr>
</thead>
<tbody>
<tr>
<td style="text-align:center">1</td>
<td style="text-align:center">SIGHUP</td>
<td style="text-align:center">挂起进程</td>
</tr>
<tr>
<td style="text-align:center">2</td>
<td style="text-align:center">SIGINT</td>
<td style="text-align:center">终止进程</td>
</tr>
<tr>
<td style="text-align:center">3</td>
<td style="text-align:center">SIGQUIT</td>
<td style="text-align:center">停止进程</td>
</tr>
<tr>
<td style="text-align:center">9</td>
<td style="text-align:center">SIGKILL</td>
<td style="text-align:center">无条件终止进程</td>
</tr>
<tr>
<td style="text-align:center">15</td>
<td style="text-align:center">SIGTERM</td>
<td style="text-align:center">尽可能终止进程</td>
</tr>
<tr>
<td style="text-align:center">17</td>
<td style="text-align:center">SIGSTOP</td>
<td style="text-align:center">无条件停止进程，但不是终止进程</td>
</tr>
<tr>
<td style="text-align:center">18</td>
<td style="text-align:center">SIGTSTP</td>
<td style="text-align:center">停止或暂停进程，但不是终止进程</td>
</tr>
<tr>
<td style="text-align:center">19</td>
<td style="text-align:center">SIGCONT</td>
<td style="text-align:center">继续运行停止的进程</td>
</tr>
</tbody>
</table>
<p>默认情况下，bash shell会忽略收到的任何<code>SIGQUIT</code>和<code>SIGTERM</code>信号（所以交互式shell不会被终止）。但是bash shell会处理收到的<code>SIGHUP</code>和<code>SIGINT</code>信号。</p>
<p>Shell会将这些信号传给shell脚本程序来处理。而shell脚本默认是忽略这些信号的，为了避免它，我们可以在脚本中加入识别信号的代码，并执行命令来处理信号。</p>
<h3 id="生成信号"><a href="#生成信号" class="headerlink" title="生成信号"></a>生成信号</h3><p>键盘上的组合可以生成两种基本的Linux信号。它在停止或暂停失控程序时非常有用。</p>
<ol>
<li><p>中断程序： 使用<code>Ctrl</code>+<code>C</code>，它会发送<code>SIGINT</code>信号。</p>
<p><del>（测试没起作用，尴尬了～）</del></p>
</li>
<li><p>暂停进程：使用<code>Ctrl</code>+<code>Z</code>，它会发送<code>SIGTSTP</code>信号。</p>
<figure class="highlight shell"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br></pre></td><td class="code"><pre><span class="line">wsx@wsx-ubuntu:~$ sleep 1000</span><br><span class="line">^Z</span><br><span class="line">[2]+  已停止               sleep 1000</span><br></pre></td></tr></table></figure>
</li>
</ol>
<p><strong>注意</strong>：停止进程会让程序继续保留在内存中，并能从上次停止的位置继续运行。</p>
<p>方括号中的数字是shell自动为程序分配的<em>作业号</em>。shell将shell中运行的每个进程成为<em>作业</em>，并为其分配唯一的作业号。</p>
<p>退出shell时发现有停止的进程，用<code>ps</code>命令查看</p>
<figure class="highlight shell"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br></pre></td><td class="code"><pre><span class="line">wsx@wsx-ubuntu:~$ exit</span><br><span class="line">exit</span><br><span class="line">有停止的任务。</span><br><span class="line">wsx@wsx-ubuntu:~$ ps -l</span><br><span class="line">F S   UID   PID  PPID  C PRI  NI ADDR SZ WCHAN  TTY          TIME CMD</span><br><span class="line">0 S  1000  5438  5433  0  80   0 -  6153 wait   pts/4    00:00:00 bash</span><br><span class="line">0 T  1000  5452  5438  0  80   0 -  2258 signal pts/4    00:00:00 sleep</span><br><span class="line">0 T  1000  5456  5438  0  80   0 -  2258 signal pts/4    00:00:00 sleep</span><br><span class="line">4 R  1000  5525  5438  0  80   0 -  7665 -      pts/4    00:00:00 ps</span><br></pre></td></tr></table></figure>
<p>在表示进程状态的S列中，<code>ps</code>命令将已经停止作业的状态显示为<code>T</code>。这说明命令要么被跟踪，要么被停止了。</p>
<p>如果你仍想退出shell，只需要再输入一遍<code>exit</code>。也可以用<code>kill</code>生成<code>SIGKILL</code>信号标识上<code>PID</code>杀死进程。</p>
<figure class="highlight shell"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br></pre></td><td class="code"><pre><span class="line">wsx@wsx-ubuntu:~$ kill 5456</span><br><span class="line">wsx@wsx-ubuntu:~$ kill -9 5456</span><br><span class="line">wsx@wsx-ubuntu:~$ kill -9 5452</span><br><span class="line">[1]-  已杀死               sleep 1000</span><br><span class="line">[2]+  已杀死               sleep 1000</span><br></pre></td></tr></table></figure>
<h3 id="捕获信号"><a href="#捕获信号" class="headerlink" title="捕获信号"></a>捕获信号</h3><p><code>trap</code>命令允许我们来指定shell脚本要监看并从shell中拦截的Linux信号。</p>
<p>格式为：</p>
<figure class="highlight shell"><table><tr><td class="gutter"><pre><span class="line">1</span><br></pre></td><td class="code"><pre><span class="line">trap commands signals</span><br></pre></td></tr></table></figure>
<p>下面展示一个简单的例子，看如何使用<code>trap</code>命令忽略<code>SIGINT</code>信号，并控制脚本的行为。</p>
<figure class="highlight shell"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br></pre></td><td class="code"><pre><span class="line">wangsx@SC-201708020022:~/tmp$ cat test1.sh</span><br><span class="line"><span class="meta">#</span><span class="bash">!/bin/bash</span></span><br><span class="line"><span class="meta">#</span><span class="bash"> Testing signal trapping</span></span><br><span class="line"><span class="meta">#</span><span class="bash"></span></span><br><span class="line">trap "echo ' Sorry! I have trapped Ctrl-C'" SIGINT</span><br><span class="line"><span class="meta">#</span><span class="bash"></span></span><br><span class="line">echo This is a test script</span><br><span class="line"><span class="meta">#</span><span class="bash"></span></span><br><span class="line">count=1</span><br><span class="line">while [ $count -le 10 ]</span><br><span class="line">do</span><br><span class="line">    echo "Loop #$count"</span><br><span class="line">    sleep 1</span><br><span class="line">    count=$[ $count + 1 ]</span><br><span class="line">done</span><br><span class="line"><span class="meta">#</span><span class="bash"></span></span><br><span class="line">echo "This is the end of the test script"</span><br><span class="line"><span class="meta">#</span><span class="bash"></span></span><br></pre></td></tr></table></figure>
<p>来运行测试一下：</p>
<figure class="highlight shell"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br></pre></td><td class="code"><pre><span class="line">wangsx@SC-201708020022:~/tmp$ ./test1.sh</span><br><span class="line">This is a test script</span><br><span class="line">Loop #1</span><br><span class="line">Loop #2</span><br><span class="line">Loop #3</span><br><span class="line">Loop #4</span><br><span class="line">Loop #5</span><br><span class="line">Loop #6</span><br><span class="line">^C Sorry! I have trapped Ctrl-C</span><br><span class="line">Loop #7</span><br><span class="line">Loop #8</span><br><span class="line">Loop #9</span><br><span class="line">Loop #10</span><br><span class="line">This is the end of the test script</span><br></pre></td></tr></table></figure>
<h3 id="捕获信号-1"><a href="#捕获信号-1" class="headerlink" title="捕获信号"></a>捕获信号</h3><p>我们也可以在shell脚本退出时进行捕获。这是<strong>在shell完成任务时执行命令的一种简便方法</strong>。</p>
<figure class="highlight shell"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br></pre></td><td class="code"><pre><span class="line">wangsx@SC-201708020022:~/tmp$ cat test2.sh</span><br><span class="line"><span class="meta">#</span><span class="bash">!/bin/bash</span></span><br><span class="line"><span class="meta">#</span><span class="bash"> Trapping the script <span class="built_in">exit</span></span></span><br><span class="line"><span class="meta">#</span><span class="bash"></span></span><br><span class="line">trap "echo Goodbye..." EXIT</span><br><span class="line"><span class="meta">#</span><span class="bash"></span></span><br><span class="line">count=1</span><br><span class="line">while [ $count -le 5 ]</span><br><span class="line">do</span><br><span class="line">    echo "Loop #$count"</span><br><span class="line">    sleep 1</span><br><span class="line">    count=$[ $count + 1 ]</span><br><span class="line">done</span><br><span class="line"><span class="meta">#</span><span class="bash"></span></span><br><span class="line"></span><br><span class="line">wangsx@SC-201708020022:~/tmp$ ./test2.sh</span><br><span class="line">Loop #1</span><br><span class="line">Loop #2</span><br><span class="line">Loop #3</span><br><span class="line">Loop #4</span><br><span class="line">Loop #5</span><br><span class="line">Goodbye...</span><br></pre></td></tr></table></figure>
<p>当该脚本运行到退出位置，捕获就触发了，shell会执行在<code>trap</code>命令行指定的命令。就算提取退出，也能够成功捕获。</p>
<h3 id="修改或移除捕获"><a href="#修改或移除捕获" class="headerlink" title="修改或移除捕获"></a>修改或移除捕获</h3><p>想在不同的位置进行不同的捕获处理，只需要重新使用带新选项的<code>trap</code>命令。</p>
<figure class="highlight shell"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br><span class="line">27</span><br><span class="line">28</span><br><span class="line">29</span><br><span class="line">30</span><br><span class="line">31</span><br><span class="line">32</span><br><span class="line">33</span><br><span class="line">34</span><br><span class="line">35</span><br><span class="line">36</span><br><span class="line">37</span><br></pre></td><td class="code"><pre><span class="line">wangsx@SC-201708020022:~/tmp$ cat test3.sh</span><br><span class="line"><span class="meta">#</span><span class="bash">!/bin/bash</span></span><br><span class="line"><span class="meta">#</span><span class="bash"> Modifying a <span class="built_in">set</span> <span class="built_in">trap</span></span></span><br><span class="line"><span class="meta">#</span><span class="bash"></span></span><br><span class="line">trap "echo ' Sorry... Ctrc-C is trapped.'" SIGINT # SIGINT是退出信号</span><br><span class="line"><span class="meta">#</span><span class="bash"></span></span><br><span class="line">count=1</span><br><span class="line">while [ $count -le 5 ]  # 当count&lt;5的时候</span><br><span class="line">do</span><br><span class="line">    echo "Loop #$count"</span><br><span class="line">    sleep 1    # 睡1秒</span><br><span class="line">    count=$[ $count + 1 ]</span><br><span class="line">done</span><br><span class="line"></span><br><span class="line"><span class="meta">#</span><span class="bash"></span></span><br><span class="line">trap "echo ' I modified the trap!'" SIGINT</span><br><span class="line"><span class="meta">#</span><span class="bash"></span></span><br><span class="line">count=1</span><br><span class="line">while [ $count -le 5 ]  # 当count&lt;5的时候</span><br><span class="line">do</span><br><span class="line">    echo "Loop #$count"</span><br><span class="line">    sleep 1    # 睡1秒</span><br><span class="line">    count=$[ $count + 1 ]</span><br><span class="line">done</span><br><span class="line">wangsx@SC-201708020022:~/tmp$ ./test3.sh</span><br><span class="line">Loop #1</span><br><span class="line">Loop #2</span><br><span class="line">Loop #3</span><br><span class="line">^C Sorry... Ctrc-C is trapped.</span><br><span class="line">Loop #4</span><br><span class="line">Loop #5</span><br><span class="line">Loop #1</span><br><span class="line">Loop #2</span><br><span class="line">Loop #3</span><br><span class="line">^C I modified the trap!</span><br><span class="line">Loop #4</span><br><span class="line">Loop #5</span><br></pre></td></tr></table></figure>
<p>相当于两次不同的捕获。</p>
<p>我们也可以删除已经设置好的捕获。</p>
<figure class="highlight shell"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br><span class="line">27</span><br><span class="line">28</span><br><span class="line">29</span><br><span class="line">30</span><br><span class="line">31</span><br><span class="line">32</span><br><span class="line">33</span><br><span class="line">34</span><br><span class="line">35</span><br><span class="line">36</span><br></pre></td><td class="code"><pre><span class="line">wangsx@SC-201708020022:~/tmp$ cat test3.sh</span><br><span class="line"><span class="meta">#</span><span class="bash">!/bin/bash</span></span><br><span class="line"><span class="meta">#</span><span class="bash"> Modifying a <span class="built_in">set</span> <span class="built_in">trap</span></span></span><br><span class="line"><span class="meta">#</span><span class="bash"></span></span><br><span class="line">trap "echo ' Sorry... Ctrc-C is trapped.'" SIGINT # SIGINT是退出信号  在这里设置捕获</span><br><span class="line"><span class="meta">#</span><span class="bash"></span></span><br><span class="line">count=1</span><br><span class="line">while [ $count -le 5 ]  # 当count&lt;5的时候</span><br><span class="line">do</span><br><span class="line">    echo "Loop #$count"</span><br><span class="line">    sleep 1    # 睡1秒</span><br><span class="line">    count=$[ $count + 1 ]</span><br><span class="line">done</span><br><span class="line"></span><br><span class="line"><span class="meta">#</span><span class="bash"></span></span><br><span class="line">trap -- SIGINT # 在这里删除捕获</span><br><span class="line">echo "I modified the trap!"</span><br><span class="line"><span class="meta">#</span><span class="bash"></span></span><br><span class="line">count=1</span><br><span class="line">while [ $count -le 5 ]  # 当count&lt;5的时候</span><br><span class="line">do</span><br><span class="line">    echo "Loop #$count"</span><br><span class="line">    sleep 1    # 睡1秒</span><br><span class="line">    count=$[ $count + 1 ]</span><br><span class="line">done</span><br><span class="line">wangsx@SC-201708020022:~/tmp$ ./test3.sh</span><br><span class="line">Loop #1</span><br><span class="line">Loop #2</span><br><span class="line">Loop #3</span><br><span class="line">Loop #4</span><br><span class="line">Loop #5</span><br><span class="line">I modified the trap!</span><br><span class="line">Loop #1</span><br><span class="line">Loop #2</span><br><span class="line">Loop #3</span><br><span class="line">^C</span><br></pre></td></tr></table></figure>
<p>信号捕获被移除之后，脚本会按照原来的方式处理<code>SIGINT</code>信号。所以使用<code>Ctrl+C</code>键时，脚本运行会退出。当然，如果是在这个信号捕获移除前接受到<code>SIGINT</code>信号，那么脚本还是会捕获。（因为shell脚本运行是按步的，前面没有接收到信号捕获的移除，自然不会实现信号捕获的移除）</p>
<h2 id="以后台模式运行脚本"><a href="#以后台模式运行脚本" class="headerlink" title="以后台模式运行脚本"></a>以后台模式运行脚本</h2><h3 id="后台运行脚本"><a href="#后台运行脚本" class="headerlink" title="后台运行脚本"></a>后台运行脚本</h3><p>以后台模式运行shell脚本非常简单，只要再命令后加<code>&amp;</code>符就可以了。</p>
<figure class="highlight shell"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br></pre></td><td class="code"><pre><span class="line">wangsx@SC-201708020022:~$ cat test4.sh</span><br><span class="line"><span class="meta">#</span><span class="bash">!/bin/bash</span></span><br><span class="line"><span class="meta">#</span><span class="bash"> Testing running <span class="keyword">in</span> the background</span></span><br><span class="line"><span class="meta">#</span><span class="bash"></span></span><br><span class="line">count=1</span><br><span class="line">while [ $count -le 10 ]</span><br><span class="line">do</span><br><span class="line">    sleep 1</span><br><span class="line">    count=$[ $count + 1 ]</span><br><span class="line">done</span><br><span class="line">wangsx@SC-201708020022:~$ ./test4.sh &amp;</span><br><span class="line">[1] 69</span><br></pre></td></tr></table></figure>
<p>当添加<code>&amp;</code>符号后，命令和bash shell会分离而作为一个独立的后台进行运行。并返回作业号（方括号内）和进程ID（PID），Linux系统上运行的每一个进程都必须有一个唯一的PID。</p>
<p>当后台进程结束后，它会在终端显示出消息：</p>
<figure class="highlight shell"><table><tr><td class="gutter"><pre><span class="line">1</span><br></pre></td><td class="code"><pre><span class="line">[1]   已完成               ./test4.sh</span><br></pre></td></tr></table></figure>
<p>需要注意的是，当后台程序运行时，它仍然会使用终端显示器显示<code>STDOUT</code>和<code>STDERR</code>消息。最好是将<code>STDOUT</code>和<code>STDERR</code>进行重定向。</p>
<h3 id="运行多个后台作业"><a href="#运行多个后台作业" class="headerlink" title="运行多个后台作业"></a>运行多个后台作业</h3><p>我们可以在命令提示符中同时启动多个后台作用，然后用<code>ps</code>命令查看。</p>
<figure class="highlight shell"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br></pre></td><td class="code"><pre><span class="line">wangsx@SC-201708020022:~$ ./test4.sh &amp;</span><br><span class="line">[1] 117</span><br><span class="line">wangsx@SC-201708020022:~$ ./test5.sh &amp;</span><br><span class="line">[2] 122</span><br><span class="line">wangsx@SC-201708020022:~$ ./test6.sh &amp;</span><br><span class="line">[3] 128</span><br><span class="line">wangsx@SC-201708020022:~$ ps</span><br><span class="line">  PID TTY          TIME CMD</span><br><span class="line">    2 tty1     00:00:00 bash</span><br><span class="line">  117 tty1     00:00:00 test4.sh</span><br><span class="line">  122 tty1     00:00:00 test5.sh</span><br><span class="line">  128 tty1     00:00:00 test6.sh</span><br><span class="line">  135 tty1     00:00:00 sleep</span><br><span class="line">  136 tty1     00:00:00 sleep</span><br><span class="line">  137 tty1     00:00:00 ps</span><br><span class="line">  138 tty1     00:00:00 sleep</span><br></pre></td></tr></table></figure>
<p>我们特别需要注意，如果终端退出，后台程序也会随之退出。</p>
<h2 id="在非控制台下运行脚本"><a href="#在非控制台下运行脚本" class="headerlink" title="在非控制台下运行脚本"></a>在非控制台下运行脚本</h2><p>如果我们不想出现终端退出后台程序退出的情况，可以使用<code>nohup</code>命令来实现。</p>
<p><strong><code>nohup</code>命令运行了另外一个命令来阻断所有发送给该进程的<code>SIGHUP</code>信号。这会在退出终端会话时阻止进程退出。</strong></p>
<p>其格式如下：</p>
<figure class="highlight shell"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br></pre></td><td class="code"><pre><span class="line">wangsx@SC-201708020022:~$ nohup ./test4.sh  &amp;</span><br><span class="line">[1] 156</span><br><span class="line">wangsx@SC-201708020022:~$ nohup: 忽略输入并把输出追加到'nohup.out'</span><br></pre></td></tr></table></figure>
<p>由于<code>nohup</code>命令会解除终端与进程的关联，进程也就不再同<code>STDOUT</code>和<code>STDERR</code>联系在一起。它会自动将这两者重定向到名为<code>nohup.out</code>的文件中。</p>
<h2 id="作业控制"><a href="#作业控制" class="headerlink" title="作业控制"></a>作业控制</h2><p>启动、停止终止以及恢复作业统称为<strong>作业控制</strong>。我们可以通过这几种方式完全控制shell环境中所有的进程的运行方式。</p>
<h3 id="查看作业"><a href="#查看作业" class="headerlink" title="查看作业"></a>查看作业</h3><p>作业控制的<strong>关键命令</strong>是<code>jobs</code>命令。它允许查看shell当前正在处理的作业。</p>
<figure class="highlight shell"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br></pre></td><td class="code"><pre><span class="line">wangsx@SC-201708020022:~$ cat test10.sh</span><br><span class="line"><span class="meta">#</span><span class="bash">!/bin/bash</span></span><br><span class="line"><span class="meta">#</span><span class="bash"> Test job control</span></span><br><span class="line"><span class="meta">#</span><span class="bash"></span></span><br><span class="line">echo "Script Process ID: $$"</span><br><span class="line"><span class="meta">#</span><span class="bash"></span></span><br><span class="line">count=1</span><br><span class="line">while [ $count -le 10 ]</span><br><span class="line">do</span><br><span class="line">    echo "Loop #$count"</span><br><span class="line">    sleep 10</span><br><span class="line">    count=$[ $count + 1 ]</span><br><span class="line">done</span><br><span class="line"><span class="meta">#</span><span class="bash"></span></span><br><span class="line">echo "End of script..."</span><br><span class="line"><span class="meta">#</span><span class="bash"></span></span><br><span class="line">wangsx@SC-201708020022:~$ ./test10.sh</span><br><span class="line">Script Process ID: 27</span><br><span class="line">Loop #1</span><br><span class="line">Loop #2</span><br><span class="line">^Z^C # 我的ctrl+z好像不起作用</span><br></pre></td></tr></table></figure>
<p>脚本用<code>$$</code>变量来显示系统分配给脚本的PID。使用Ctrl+Z组合键来停止脚本（我的在这不起作用~之前好像也是）。</p>
<p>我们使用同样的脚本，利用<code>&amp;</code>将另外一个作业作为后台进程启动。我们通过<code>jobs -l</code>命令查看作业的PID。</p>
<figure class="highlight shell"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br></pre></td><td class="code"><pre><span class="line">wangsx@SC-201708020022:~/tmp$ ./test10.sh &gt; test10.out &amp;</span><br><span class="line">[1] 121</span><br><span class="line">wangsx@SC-201708020022:~/tmp$ jobs -l</span><br><span class="line">[1]+   121 运行中               ./test10.sh &gt; test10.out &amp;</span><br></pre></td></tr></table></figure>
<p>下面看<code>jobs</code>命令的一些参数：</p>
<table>
<thead>
<tr>
<th>参数</th>
<th>语法</th>
</tr>
</thead>
<tbody>
<tr>
<td>-l</td>
<td>列出进程的PID以及作业号</td>
</tr>
<tr>
<td>-n</td>
<td>只列出上次shell发出的通知后改变了状态的作业</td>
</tr>
<tr>
<td>-p</td>
<td>只列出作业的PID</td>
</tr>
<tr>
<td>-r</td>
<td>只列出运行中的作业</td>
</tr>
<tr>
<td>-s</td>
<td>只列出已停止的作业</td>
</tr>
</tbody>
</table>
<p>如果仔细注意的话，我们发现作业号后面有<code>+</code>号。带加号的作业会被当成默认作业。当前的默认作业完成处理后，带减号的作业成为下一个默认作业。任何时候只有一个带加号的作业和一个带减号的作业。</p>
<figure class="highlight shell"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br></pre></td><td class="code"><pre><span class="line">wangsx@SC-201708020022:~/tmp$ jobs -l</span><br><span class="line">[1]    132 运行中               ./test10.sh &gt; test10.out &amp;</span><br><span class="line">[2]-   134 运行中               ./test10.sh &gt; test10.out &amp;</span><br><span class="line">[3]+   136 运行中               ./test10.sh &gt; test10.out &amp;</span><br></pre></td></tr></table></figure>
<p>可以发现最好运行的脚本输出排在最前面。</p>
<p>我们调用了<code>kill</code>命令向默认进程发送了一个<code>SIGHUP</code>信号，终止了该作业。</p>
<figure class="highlight shell"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br></pre></td><td class="code"><pre><span class="line">wangsx@SC-201708020022:~/tmp$ ./test10.sh &gt; test10.out &amp;</span><br><span class="line">[1] 165</span><br><span class="line">wangsx@SC-201708020022:~/tmp$ ./test10.sh &gt; test10.out &amp;</span><br><span class="line">[2] 167</span><br><span class="line">wangsx@SC-201708020022:~/tmp$ ./test10.sh &gt; test10.out &amp;</span><br><span class="line">[3] 169</span><br><span class="line">wangsx@SC-201708020022:~/tmp$ jobs -l</span><br><span class="line">[1]    165 运行中               ./test10.sh &gt; test10.out &amp;</span><br><span class="line">[2]-   167 运行中               ./test10.sh &gt; test10.out &amp;</span><br><span class="line">[3]+   169 运行中               ./test10.sh &gt; test10.out &amp;</span><br><span class="line">wangsx@SC-201708020022:~/tmp$ kill 169</span><br><span class="line">wangsx@SC-201708020022:~/tmp$ jobs -l</span><br><span class="line">[1]    165 运行中               ./test10.sh &gt; test10.out &amp;</span><br><span class="line">[2]-   167 运行中               ./test10.sh &gt; test10.out &amp;</span><br><span class="line">[3]+   169 已终止               ./test10.sh &gt; test10.out</span><br><span class="line">wangsx@SC-201708020022:~/tmp$ jobs -l</span><br><span class="line">[1]-   165 运行中               ./test10.sh &gt; test10.out &amp;</span><br><span class="line">[2]+   167 运行中               ./test10.sh &gt; test10.out &amp;</span><br></pre></td></tr></table></figure>
<h3 id="重启停止的作业"><a href="#重启停止的作业" class="headerlink" title="重启停止的作业"></a>重启停止的作业</h3><p>我们可以将已经停止的作业作为后台进程或者前台进程重启。前台进程会接管当前工作的终端，所以使用时需要注意。</p>
<p>要以后台模式重启一个作业，可以用<code>bg</code>命令加上作业号（我的Window10子系统好像确实不能使用Ctrl+Z的功能，有兴趣可以自己测试一下）。</p>
<figure class="highlight shell"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br></pre></td><td class="code"><pre><span class="line">wangsx@SC-201708020022:~/tmp$ ./test10.sh</span><br><span class="line">Script Process ID: 13</span><br><span class="line">Loop #1</span><br><span class="line">^ZLoop #2</span><br><span class="line">^C</span><br><span class="line">wangsx@SC-201708020022:~/tmp$ bg</span><br><span class="line">bash: bg: 当前: 无此任务</span><br><span class="line">wangsx@SC-201708020022:~/tmp$ jobs</span><br></pre></td></tr></table></figure>
<p>如果是默认作业，只需要使用<code>bg</code>命令。如果有多个作业，你得在<code>bg</code>命令后加上作业号。</p>
<h2 id="调整谦让度"><a href="#调整谦让度" class="headerlink" title="调整谦让度"></a>调整谦让度</h2><p>在Linux中，内核负责将CPU时间分配给系统上运行的每一个进程。<strong>调度优先级</strong>是内核分配给进程的CPU时间。在Linux系统中，由shell启动的所有进程的调度优先级默认都是相同的。</p>
<p>调度优先级是一个整数值，从-20（最高）到+19（最低）。默认bash shell以优先级0来启动所有进程。</p>
<p>我们可以使用<code>nice</code>命令来改变shell脚本的优先级。</p>
<h3 id="nice命令"><a href="#nice命令" class="headerlink" title="nice命令"></a>nice命令</h3><p>要让命令以更低的优先级运行，只要用<code>nice</code>的<code>-n</code>命令行来指定新的优先级级别。</p>
<figure class="highlight shell"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br></pre></td><td class="code"><pre><span class="line">wsx@ubuntu:~/tmp$ nice -n 10 ./test10.sh &gt; test10.out &amp;</span><br><span class="line">[5] 18953</span><br><span class="line">wsx@ubuntu:~/tmp$ ps -p 18953 -o pid,ppid,ni,cmd</span><br><span class="line">   PID   PPID  NI CMD</span><br><span class="line"> 18953  18782  10 /bin/bash ./test10.sh</span><br></pre></td></tr></table></figure>
<p>如果想要提高优先级，需要使用超级用户权限。<code>nice</code>命令的<code>-n</code>选项不是必须的，只需要在破折号后面跟上优先级就行了。</p>
<figure class="highlight shell"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br></pre></td><td class="code"><pre><span class="line">wsx@ubuntu:~/tmp$ nice -10 ./test10.sh &gt; test10.out &amp;</span><br><span class="line">[6] 18999</span><br><span class="line">[5]   Done                    nice -n 10 ./test10.sh &gt; test10.out</span><br><span class="line">wsx@ubuntu:~/tmp$ ps -p 18999 -o pid,ppid,ni,cmd</span><br><span class="line">   PID   PPID  NI CMD</span><br><span class="line"> 18999  18782  10 /bin/bash ./test10.sh</span><br></pre></td></tr></table></figure>
<h3 id="renice命令"><a href="#renice命令" class="headerlink" title="renice命令"></a>renice命令</h3><p>有时候我们想要改变系统上已经运行命令的优先级，这是<code>renice</code>命令可以做到的。它允许我们指定PID来改变它的优先级。</p>
<figure class="highlight shell"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br></pre></td><td class="code"><pre><span class="line">wsx@ubuntu:~/tmp$ ./test10.sh &amp;</span><br><span class="line">[3] 19086</span><br><span class="line">wsx@ubuntu:~$ ps -p 19086 -o pid,ppid,ni,cmd</span><br><span class="line">   PID   PPID  NI CMD</span><br><span class="line"> 19086  19070   0 /bin/bash ./test10.sh</span><br><span class="line">wsx@ubuntu:~$ renice -n 10 -p 19086</span><br><span class="line">19086 (process ID) old priority 0, new priority 10</span><br><span class="line">wsx@ubuntu:~$ ps -p 19086 -o pid,ppid,ni,cmd</span><br><span class="line">   PID   PPID  NI CMD</span><br><span class="line"> 19086  19070  10 /bin/bash ./test10.sh</span><br></pre></td></tr></table></figure>
<h2 id="定时运行脚本"><a href="#定时运行脚本" class="headerlink" title="定时运行脚本"></a>定时运行脚本</h2><p>Linux系统提供了多个在预定时间运行脚本的方法：<code>at</code>命令和<code>cron</code>表。</p>
<h3 id="用at命令来计划执行任务"><a href="#用at命令来计划执行任务" class="headerlink" title="用at命令来计划执行任务"></a>用at命令来计划执行任务</h3><p><code>at</code>命令允许指定Linux系统何时运行脚本。<code>at</code>命令会将作业提交到队列中，指定shell何时运行该作业。<code>at</code>的守护进程<code>atd</code>会以后台模式运行，检查作业队列来运行作业。</p>
<p><code>atd</code>守护进程会检查系统上的一个特殊目录（通常位于<code>/var/spool/at</code>）来获取用<code>at</code>命令提交的作业。</p>
<h4 id="at命令的格式"><a href="#at命令的格式" class="headerlink" title="at命令的格式"></a>at命令的格式</h4><figure class="highlight shell"><table><tr><td class="gutter"><pre><span class="line">1</span><br></pre></td><td class="code"><pre><span class="line">at [-f filename] time</span><br></pre></td></tr></table></figure>
<p>默认，<code>at</code>命令会将<code>STDIN</code>的输入放入队列中。我们可以用<code>-f</code>参数来指定用于读取命令的文件名。<code>time</code>参数指定了Linux系统何时运行该脚本。</p>
<p><code>at</code>命令能识别多种不同的时间格式。</p>
<ul>
<li>标准的小时和分钟格式，比如10:15</li>
<li>AM/PM指示符，比如10:15 PM</li>
<li>特定可命令的时间，比如now, noon, midnight或teatime （4 PM）</li>
</ul>
<p>除了指定运行时间，还可以指定运行的日期。</p>
<ul>
<li>标准日期格式，比如MMDDYY, MM/DD/YY或DD.MM.YY</li>
<li>文本日期，比如Jul 4或Dec 25，加不加年份都可以</li>
<li>还可以指定时间增量<ul>
<li>当前时间+25min</li>
<li>明天10:15PM</li>
<li>10:15+7天</li>
</ul>
</li>
</ul>
<p>针对不同的优先级，存在26种不同的作业队列。作业队列通常用小写字母a-z和大写字母A-Z来指代。</p>
<p>作业队列的字母排序越高，作业运行的优先级就越低（更高的nice值）。可以用<code>-q</code>参数指定不同的队列字母。</p>
<h4 id="获取作业的输出"><a href="#获取作业的输出" class="headerlink" title="获取作业的输出"></a>获取作业的输出</h4><p>Linux系统会将提交作业的用户的电子邮件地址作为STDOUT和STDERR。任何发到STDOUT或STDERR的输出都会通过邮件系统发送给用户。</p>
<figure class="highlight shell"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br></pre></td><td class="code"><pre><span class="line"><span class="meta">#</span><span class="bash"> 解决atd没启动的问题</span></span><br><span class="line">wangsx@SC-201708020022:~/tmp$ sudo /etc/init.d/atd start</span><br></pre></td></tr></table></figure>
<figure class="highlight shell"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br></pre></td><td class="code"><pre><span class="line">wangsx@SC-201708020022:~/tmp$ cat test13.sh</span><br><span class="line"><span class="meta">#</span><span class="bash">!/bin/bash</span></span><br><span class="line"><span class="meta">#</span><span class="bash"> Test using at <span class="built_in">command</span></span></span><br><span class="line"><span class="meta">#</span><span class="bash"></span></span><br><span class="line">echo "This script ran at $(date +%B%d,%T)"</span><br><span class="line">echo</span><br><span class="line">sleep 5</span><br><span class="line">echo "This is the script's end..."</span><br><span class="line"><span class="meta">#</span><span class="bash"></span></span><br><span class="line">wangsx@SC-201708020022:~/tmp$ at -f test13.sh now</span><br><span class="line">warning: commands will be executed using /bin/sh</span><br><span class="line">job 4 at Tue Sep 26 12:12:00 2017</span><br></pre></td></tr></table></figure>
<p><code>at</code>命令会显示分配给作业的作业号以及为作业安排的运行时间。<code>at</code>命令利用<code>sendmail</code>应用程序来发送邮件。如果没有安装这个工具就无法获得输出，因此在使用<code>at</code>命令时，最好在脚本中对STDOUT和STDERR进行重定向。</p>
<figure class="highlight shell"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br></pre></td><td class="code"><pre><span class="line">wangsx@SC-201708020022:~/tmp$ cat test13b.sh</span><br><span class="line"><span class="meta">#</span><span class="bash">!/bin/bash</span></span><br><span class="line"><span class="meta">#</span><span class="bash"> Test using at <span class="built_in">command</span></span></span><br><span class="line"><span class="meta">#</span><span class="bash"></span></span><br><span class="line">echo "This script ran at $(date +%B%d,%T)" &gt; test13b.out</span><br><span class="line">echo &gt;&gt; test13b.out</span><br><span class="line">sleep 5</span><br><span class="line">echo "This is the script's end..." &gt;&gt; test13b.out</span><br><span class="line"><span class="meta">#</span><span class="bash"></span></span><br><span class="line">wangsx@SC-201708020022:~/tmp$ at -M -f test13b.sh now</span><br><span class="line">warning: commands will be executed using /bin/sh</span><br><span class="line">job 7 at Tue Sep 26 12:16:00 2017</span><br><span class="line">wangsx@SC-201708020022:~/tmp$ cat test13b.out</span><br><span class="line">This script ran at 九月26,12:16:24</span><br><span class="line"></span><br><span class="line">This is the script's end...</span><br></pre></td></tr></table></figure>
<p>这里使用了<code>-M</code>选项来屏蔽作业产生的输出信息。</p>
<h4 id="列出等待的作业"><a href="#列出等待的作业" class="headerlink" title="列出等待的作业"></a>列出等待的作业</h4><p><code>atq</code>命令可以查看系统中有哪些作业再等待。</p>
<figure class="highlight shell"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br></pre></td><td class="code"><pre><span class="line">wangsx@SC-201708020022:~/tmp$ at -M -f test13b.sh teatime</span><br><span class="line">warning: commands will be executed using /bin/sh</span><br><span class="line">job 11 at Wed Sep 27 16:00:00 2017</span><br><span class="line">Can't open /var/run/atd.pid to signal atd. No atd running?</span><br><span class="line">wangsx@SC-201708020022:~/tmp$ sudo /etc/init.d/atd start</span><br><span class="line">[sudo] wangsx 的密码：</span><br><span class="line"> * Starting deferred execution scheduler atd                                                                     [ OK ]</span><br><span class="line">wangsx@SC-201708020022:~/tmp$ at -M -f test13b.sh teatime</span><br><span class="line">warning: commands will be executed using /bin/sh</span><br><span class="line">job 12 at Wed Sep 27 16:00:00 2017</span><br><span class="line">wangsx@SC-201708020022:~/tmp$ at -M -f test13b.sh tomorrow</span><br><span class="line">warning: commands will be executed using /bin/sh</span><br><span class="line">job 13 at Wed Sep 27 21:44:00 2017</span><br><span class="line">wangsx@SC-201708020022:~/tmp$ at -M -f test13b.sh 13:30</span><br><span class="line">warning: commands will be executed using /bin/sh</span><br><span class="line">job 14 at Wed Sep 27 13:30:00 2017</span><br><span class="line">wangsx@SC-201708020022:~/tmp$ atq</span><br><span class="line">11      Wed Sep 27 16:00:00 2017 a wangsx</span><br><span class="line">12      Wed Sep 27 16:00:00 2017 a wangsx</span><br><span class="line">13      Wed Sep 27 21:44:00 2017 a wangsx</span><br><span class="line">14      Wed Sep 27 13:30:00 2017 a wangsx</span><br></pre></td></tr></table></figure>
<p>作业列表中显示了作业号、系统运行该作业的日期和时间以及它所在的队列位置。</p>
<h4 id="删除作业"><a href="#删除作业" class="headerlink" title="删除作业"></a>删除作业</h4><p>使用<code>atrm</code>命令删除等待中的作业。</p>
<figure class="highlight shell"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br></pre></td><td class="code"><pre><span class="line">wangsx@SC-201708020022:~/tmp$ atq</span><br><span class="line">11      Wed Sep 27 16:00:00 2017 a wangsx</span><br><span class="line">12      Wed Sep 27 16:00:00 2017 a wangsx</span><br><span class="line">13      Wed Sep 27 21:44:00 2017 a wangsx</span><br><span class="line">14      Wed Sep 27 13:30:00 2017 a wangsx</span><br><span class="line">wangsx@SC-201708020022:~/tmp$ atrm 11</span><br><span class="line">wangsx@SC-201708020022:~/tmp$ atq</span><br><span class="line">12      Wed Sep 27 16:00:00 2017 a wangsx</span><br><span class="line">13      Wed Sep 27 21:44:00 2017 a wangsx</span><br><span class="line">14      Wed Sep 27 13:30:00 2017 a wangsx</span><br></pre></td></tr></table></figure>
<p>只能删除自己提交的作业，不能删除其他人的。</p>
<h3 id="安排需要定期执行的脚本"><a href="#安排需要定期执行的脚本" class="headerlink" title="安排需要定期执行的脚本"></a>安排需要定期执行的脚本</h3><p>如果是需要定期执行的脚本，我们不需要使用<code>at</code>不断提交作业，而是可以利用Linux系统的另一个功能。</p>
<p><strong>Linux系统使用<code>cron</code>程序来安排要定期执行的作业。它会在后台运行并检查一个特殊的表（成为cron时间表），以获得已安排执行的作业。</strong></p>
<h4 id="cron时间表"><a href="#cron时间表" class="headerlink" title="cron时间表"></a>cron时间表</h4><p><code>cron</code>时间表的格式如下：</p>
<figure class="highlight shell"><table><tr><td class="gutter"><pre><span class="line">1</span><br></pre></td><td class="code"><pre><span class="line">min hour dayofmonth month dayofweek command</span><br></pre></td></tr></table></figure>
<p><code>cron</code>时间表允许我们用特定值、取值范围（比如1-5）或者通配符（星号）来指定条目。</p>
<p>例如，我们想在每天的10:15运行一个命令，可以使用：</p>
<figure class="highlight shell"><table><tr><td class="gutter"><pre><span class="line">1</span><br></pre></td><td class="code"><pre><span class="line">15 10 * * * command</span><br></pre></td></tr></table></figure>
<p>在其中三个字段使用了通配符，表明<code>cron</code>会在每个月的每天的10:15执行该命令。</p>
<p>要指定在每周一4:15PM运行命令，可以使用：</p>
<figure class="highlight shell"><table><tr><td class="gutter"><pre><span class="line">1</span><br></pre></td><td class="code"><pre><span class="line">15 16 * * 1 command</span><br></pre></td></tr></table></figure>
<p>可以用三字符的文本值mon,tue,wed,thu,fri,sat,sum或数值（0为周日，6为周六）来指定dayofweek的表项。</p>
<p><code>dayofmonth</code>可以用1-31表示。</p>
<figure class="highlight shell"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br></pre></td><td class="code"><pre><span class="line"><span class="meta">#</span><span class="bash"> 怎么在每个月的最后一天执行命令？</span></span><br><span class="line">00 12 * * * if [`date +%d -d tomorrow` = 01 ]; then ; command</span><br></pre></td></tr></table></figure>
<p>命令列表必须指定要运行的命令或脚本的全路径名。</p>
<figure class="highlight shell"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br></pre></td><td class="code"><pre><span class="line"><span class="meta">#</span><span class="bash"> 例如</span></span><br><span class="line">15 10 * * * /home/rich/test4.sh &gt; test4out</span><br></pre></td></tr></table></figure>
<p>注意：<code>corn</code>会用提交作业的用户账户运行脚本，所以我们在操作指定文件时必须有相应权限。</p>
<h4 id="构建cron时间表"><a href="#构建cron时间表" class="headerlink" title="构建cron时间表"></a>构建cron时间表</h4><p>Linux提供了<code>crontab</code>命令来处理<code>cron</code>时间表。我们可以使用<code>-l</code>选项列出时间表。</p>
<figure class="highlight shell"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br></pre></td><td class="code"><pre><span class="line">wangsx@SC-201708020022:~/tmp$ crontab -l</span><br><span class="line">no crontab for wangsx</span><br></pre></td></tr></table></figure>
<p>要添加条目，使用<code>-e</code>选项。在添加条目时，<code>crontab</code>命令会启动一个文本编辑器，使用已有的<code>cron</code>时间表作为文件内容。</p>
<h4 id="浏览cron目录"><a href="#浏览cron目录" class="headerlink" title="浏览cron目录"></a>浏览cron目录</h4><p>如果对时间精确性要求不高，用预配置的<code>cron</code>脚本目录会更方便。有4个基本目录：hourly, daily, monthly和weekly。</p>
<figure class="highlight shell"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br></pre></td><td class="code"><pre><span class="line">wangsx@SC-201708020022:~/tmp$ ls /etc/cron.*ly</span><br><span class="line">/etc/cron.daily:</span><br><span class="line">apport      bsdmainutils  man-db   passwd                  upstart</span><br><span class="line">apt-compat  dpkg          mdadm    popularity-contest</span><br><span class="line">aptitude    logrotate     mlocate  update-notifier-common</span><br><span class="line"></span><br><span class="line">/etc/cron.hourly:</span><br><span class="line"></span><br><span class="line">/etc/cron.monthly:</span><br><span class="line"></span><br><span class="line">/etc/cron.weekly:</span><br><span class="line">fstrim  man-db  update-notifier-common</span><br></pre></td></tr></table></figure>
<p>如果脚本需要每天运行一次，只要将脚本复制到daily目录，cron每天会执行它。</p>
<h4 id="anacron程序"><a href="#anacron程序" class="headerlink" title="anacron程序"></a>anacron程序</h4><p>如果提交的作业需要运行时系统处于关机状态，<code>cron</code>不会运行那些错过的脚本。为了解决这个问题，<code>anacron</code>程序诞生了。</p>
<p>如果<code>anacron</code>知道某个作业错过了执行时间，它会尽快运行该作业。这个功能常用于进行常规日志维护的脚本。</p>
<p><code>anacron</code>程序只会处理位于<code>cron</code>目录下的程序，比如<code>/etc/cron.monthly</code>。它使用时间戳来决定作业是否在正确的计划间隔内运行了，每个<code>cron</code>目录都有个时间戳文件，该文件位于<code>/var/spool/anacron</code>。</p>
<p><code>anacron</code>程序使用自己的时间表来检查作业目录。</p>
<figure class="highlight shell"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br></pre></td><td class="code"><pre><span class="line">wsx@ubuntu:~$ sudo cat /var/spool/anacron/cron.monthly</span><br><span class="line">[sudo] password for wsx:</span><br><span class="line">20170926</span><br><span class="line">wsx@ubuntu:~$ sudo cat /etc/anacrontab</span><br><span class="line"><span class="meta">#</span><span class="bash"> /etc/anacrontab: configuration file <span class="keyword">for</span> anacron</span></span><br><span class="line"></span><br><span class="line"><span class="meta">#</span><span class="bash"> See anacron(8) and anacrontab(5) <span class="keyword">for</span> details.</span></span><br><span class="line"></span><br><span class="line">SHELL=/bin/sh</span><br><span class="line">PATH=/usr/local/sbin:/usr/local/bin:/sbin:/bin:/usr/sbin:/usr/bin</span><br><span class="line">HOME=/root</span><br><span class="line">LOGNAME=root</span><br><span class="line"></span><br><span class="line"><span class="meta">#</span><span class="bash"> These replace cron<span class="string">'s entries</span></span></span><br><span class="line">1       5       cron.daily      run-parts --report /etc/cron.daily</span><br><span class="line">7       10      cron.weekly     run-parts --report /etc/cron.weekly</span><br><span class="line">@monthly        15      cron.monthly    run-parts --report /etc/cron.monthly</span><br></pre></td></tr></table></figure>
<p><code>anacron</code>的时间表的基本格式和<code>cron</code>时间表略有不同：</p>
<figure class="highlight shell"><table><tr><td class="gutter"><pre><span class="line">1</span><br></pre></td><td class="code"><pre><span class="line">period delay identifier command</span><br></pre></td></tr></table></figure>
<p><code>period</code>定义了作业多久运行一次，以天为单位。<code>anacron</code>用此条目来检查作业的时间戳文件。<code>delay</code>条目会指定系统启动后<code>anacron</code>程序需要等待多少分钟再开始运行错过的脚本。<code>command</code>条目包含了<code>run-parts</code>程序和一个<code>cron</code>脚本目录名。<code>run-parts</code>程序负责运行目录中传给它的任何脚本。</p>
<p>注意了，<code>anacron</code>不会处理执行时间需求小于一天的脚本，所以它是不会运行<code>/etc/cron.hourly</code>的脚本。</p>
<p><code>identifier</code>条目是一种特别的非空字符串，如<code>cron-weekly</code>。它用于唯一标识日志消息和错误邮件中的作业。</p>

      
    </div>
    
  </div>
  
    
    <div class="copyright">
        <p><span>本文标题:</span><a href="">控制脚本</a></p>
        <!-- modify author information
        <p><span>文章作者:</span><a href="/" title="回到主页">王诗翔</a></p>
        -->
        <p><span>文章作者:</span>王诗翔</p>
        <p><span>发布时间:</span>2017-09-04, 00:00:00</p>
        <p><span>最后更新:</span>2018-01-27, 12:08:26</p>
        <p>
            <span>原始链接:</span><a class="post-url" href="" title="控制脚本">https://shixiangwang.github.io/2017/09/04/control_shell/</a>
            <span class="copy-path" data-clipboard-text="原文: https://shixiangwang.github.io/2017/09/04/control_shell/　　作者: 王诗翔" title="点击复制文章链接"><i class="fa fa-clipboard"></i></span>
            <script> var clipboard = new Clipboard('.copy-path'); </script>
        </p>
        <p>
            <span>许可协议:</span><i class="fa fa-creative-commons"></i> <a rel="license" href="http://creativecommons.org/licenses/by-nc-sa/4.0/" title="CC BY-NC-SA 4.0 International" target = "_blank">"署名-非商用-相同方式共享 4.0"</a> 转载请保留原文链接及作者。
        </p>
    </div>



    <nav id="article-nav">
        
            <div id="article-nav-newer" class="article-nav-title">
                <a href="../../15/Class-in-R/">
                    R中的属性与类
                </a>
            </div>
        
        
            <div id="article-nav-older" class="article-nav-title">
                <a href="../../03/Linux-data-analysis-tools/">
                    Linux数据处理命令工具
                </a>
            </div>
        
    </nav>


  
</article>

    <div id="toc" class="toc-article">
        <strong class="toc-title">文章目录</strong>
        
            <ol class="toc"><li class="toc-item toc-level-2"><a class="toc-link" href="#处理信号"><span class="toc-number">1.</span> <span class="toc-text">处理信号</span></a><ol class="toc-child"><li class="toc-item toc-level-3"><a class="toc-link" href="#Linux信号"><span class="toc-number">1.1.</span> <span class="toc-text">Linux信号</span></a></li><li class="toc-item toc-level-3"><a class="toc-link" href="#生成信号"><span class="toc-number">1.2.</span> <span class="toc-text">生成信号</span></a></li><li class="toc-item toc-level-3"><a class="toc-link" href="#捕获信号"><span class="toc-number">1.3.</span> <span class="toc-text">捕获信号</span></a></li><li class="toc-item toc-level-3"><a class="toc-link" href="#捕获信号-1"><span class="toc-number">1.4.</span> <span class="toc-text">捕获信号</span></a></li><li class="toc-item toc-level-3"><a class="toc-link" href="#修改或移除捕获"><span class="toc-number">1.5.</span> <span class="toc-text">修改或移除捕获</span></a></li></ol></li><li class="toc-item toc-level-2"><a class="toc-link" href="#以后台模式运行脚本"><span class="toc-number">2.</span> <span class="toc-text">以后台模式运行脚本</span></a><ol class="toc-child"><li class="toc-item toc-level-3"><a class="toc-link" href="#后台运行脚本"><span class="toc-number">2.1.</span> <span class="toc-text">后台运行脚本</span></a></li><li class="toc-item toc-level-3"><a class="toc-link" href="#运行多个后台作业"><span class="toc-number">2.2.</span> <span class="toc-text">运行多个后台作业</span></a></li></ol></li><li class="toc-item toc-level-2"><a class="toc-link" href="#在非控制台下运行脚本"><span class="toc-number">3.</span> <span class="toc-text">在非控制台下运行脚本</span></a></li><li class="toc-item toc-level-2"><a class="toc-link" href="#作业控制"><span class="toc-number">4.</span> <span class="toc-text">作业控制</span></a><ol class="toc-child"><li class="toc-item toc-level-3"><a class="toc-link" href="#查看作业"><span class="toc-number">4.1.</span> <span class="toc-text">查看作业</span></a></li><li class="toc-item toc-level-3"><a class="toc-link" href="#重启停止的作业"><span class="toc-number">4.2.</span> <span class="toc-text">重启停止的作业</span></a></li></ol></li><li class="toc-item toc-level-2"><a class="toc-link" href="#调整谦让度"><span class="toc-number">5.</span> <span class="toc-text">调整谦让度</span></a><ol class="toc-child"><li class="toc-item toc-level-3"><a class="toc-link" href="#nice命令"><span class="toc-number">5.1.</span> <span class="toc-text">nice命令</span></a></li><li class="toc-item toc-level-3"><a class="toc-link" href="#renice命令"><span class="toc-number">5.2.</span> <span class="toc-text">renice命令</span></a></li></ol></li><li class="toc-item toc-level-2"><a class="toc-link" href="#定时运行脚本"><span class="toc-number">6.</span> <span class="toc-text">定时运行脚本</span></a><ol class="toc-child"><li class="toc-item toc-level-3"><a class="toc-link" href="#用at命令来计划执行任务"><span class="toc-number">6.1.</span> <span class="toc-text">用at命令来计划执行任务</span></a><ol class="toc-child"><li class="toc-item toc-level-4"><a class="toc-link" href="#at命令的格式"><span class="toc-number">6.1.1.</span> <span class="toc-text">at命令的格式</span></a></li><li class="toc-item toc-level-4"><a class="toc-link" href="#获取作业的输出"><span class="toc-number">6.1.2.</span> <span class="toc-text">获取作业的输出</span></a></li><li class="toc-item toc-level-4"><a class="toc-link" href="#列出等待的作业"><span class="toc-number">6.1.3.</span> <span class="toc-text">列出等待的作业</span></a></li><li class="toc-item toc-level-4"><a class="toc-link" href="#删除作业"><span class="toc-number">6.1.4.</span> <span class="toc-text">删除作业</span></a></li></ol></li><li class="toc-item toc-level-3"><a class="toc-link" href="#安排需要定期执行的脚本"><span class="toc-number">6.2.</span> <span class="toc-text">安排需要定期执行的脚本</span></a><ol class="toc-child"><li class="toc-item toc-level-4"><a class="toc-link" href="#cron时间表"><span class="toc-number">6.2.1.</span> <span class="toc-text">cron时间表</span></a></li><li class="toc-item toc-level-4"><a class="toc-link" href="#构建cron时间表"><span class="toc-number">6.2.2.</span> <span class="toc-text">构建cron时间表</span></a></li><li class="toc-item toc-level-4"><a class="toc-link" href="#浏览cron目录"><span class="toc-number">6.2.3.</span> <span class="toc-text">浏览cron目录</span></a></li><li class="toc-item toc-level-4"><a class="toc-link" href="#anacron程序"><span class="toc-number">6.2.4.</span> <span class="toc-text">anacron程序</span></a></li></ol></li></ol></li></ol>
        
    </div>
    <style>
        .left-col .switch-btn,
        .left-col .switch-area {
            display: none;
        }
        .toc-level-3 i,
        .toc-level-3 ol {
            display: none !important;
        }
    </style>

    <input type="button" id="tocButton" value="隐藏目录"  title="点击按钮隐藏或者显示文章目录">

    <script>
        yiliaConfig.toc = ["隐藏目录", "显示目录", !!"false"];
    </script>



    
<div class="share">
    
        <div class="bdsharebuttonbox">
            <a href="#" class="fa fa-twitter bds_twi" data-cmd="twi" title="分享到推特"></a>
            <a href="#" class="fa fa-weibo bds_tsina" data-cmd="tsina" title="分享到新浪微博"></a>
            <a href="#" class="fa fa-qq bds_sqq" data-cmd="sqq" title="分享给 QQ 好友"></a>
            <a href="#" class="fa fa-files-o bds_copy" data-cmd="copy" title="复制网址"></a>
            <a href="#" class="fa fa fa-envelope-o bds_mail" data-cmd="mail" title="通过邮件分享"></a>
            <a href="#" class="fa fa-weixin bds_weixin" data-cmd="weixin" title="生成文章二维码"></a>
            <a href="#" class="fa fa-share-alt bds_more" data-cmd="more"></i></a>
        </div>
        <script>
            window._bd_share_config={
                "common":{"bdSnsKey":{},"bdText":"控制脚本　| Cloudberry　","bdMini":"2","bdMiniList":false,"bdPic":"","bdStyle":"0","bdSize":"24"},"share":{}};with(document)0[(getElementsByTagName('head')[0]||body).appendChild(createElement('script')).src='http://bdimg.share.baidu.com/static/api/js/share.js?v=89860593.js?cdnversion='+~(-new Date()/36e5)];
        </script>
    

    
</div>







    
        <section id="comments">
    <style> aside.comment-bar { margin: auto 30px; }</style>
    <div id="disqus_thread"></div>
    <script>
        var disqus_config = function(){
            this.page.url = 'https://shixiangwang.github.io/2017/09/04/control_shell/';
            this.page.identifier = '2017/09/04/control_shell/';
        };
        var loadComment = function(){
            var d = document, s = d.createElement('script');
            s.src = '//Cloudberry.disqus.com/embed.js';
            s.setAttribute('data-timestamp', +new Date());
            (d.head || d.body).appendChild(s);
        }
    </script>
    
    <script> loadComment(); </script>

</section>


    




    <div class="scroll" id="post-nav-button">
        
            <a href="../../15/Class-in-R/" title="上一篇: R中的属性与类">
                <i class="fa fa-angle-left"></i>
            </a>
        

        <a title="文章列表"><i class="fa fa-bars"></i><i class="fa fa-times"></i></a>

        
            <a href="../../03/Linux-data-analysis-tools/" title="下一篇: Linux数据处理命令工具">
                <i class="fa fa-angle-right"></i>
            </a>
        
    </div>

    <ul class="post-list"><li class="post-list-item"><a class="post-list-link" href="../../../../2018/02/26/python-basics/">两天研习Python基础</a></li><li class="post-list-item"><a class="post-list-link" href="../../../../2018/02/12/how-to-create-an-independent-figpath/">为markdown博文创建独立图片路径</a></li><li class="post-list-item"><a class="post-list-link" href="../../../../2018/02/10/easy-sapply-apply-vapply/">简单理解lapply,sapply,vapply</a></li><li class="post-list-item"><a class="post-list-link" href="../../../../2018/02/07/how-to-do-group-survival-analysis/">怎么对连续变量分组并进行生存分析</a></li><li class="post-list-item"><a class="post-list-link" href="../../../../2018/02/06/how-to-write-rmd-documents-in-hexo-system/">怎么在hexo博客系统中用Rmarkdown写文章</a></li><li class="post-list-item"><a class="post-list-link" href="../../../../2018/01/31/sed-how-to-filter-rows-before-using-command/">sed如何在执行命令前过滤特定文本行</a></li><li class="post-list-item"><a class="post-list-link" href="../../../../2018/01/31/sync-deploy-tools/">Sync deploy 命令工具</a></li><li class="post-list-item"><a class="post-list-link" href="../../../12/25/sed-and-gawk/">初识sed与awk</a></li><li class="post-list-item"><a class="post-list-link" href="../../../12/08/Git-basic-operation/">学习git</a></li><li class="post-list-item"><a class="post-list-link" href="../../../11/29/shell-create-text-menu-and-window/">使用shell创建文本菜单和窗口部件</a></li><li class="post-list-item"><a class="post-list-link" href="../../../11/26/shell-create-function/">创建和使用shell函数</a></li><li class="post-list-item"><a class="post-list-link" href="../../20/OOPinR/">R-面向对象编程</a></li><li class="post-list-item"><a class="post-list-link" href="../../15/Class-in-R/">R中的属性与类</a></li><li class="post-list-item"><a class="post-list-link" href="">控制脚本</a></li><li class="post-list-item"><a class="post-list-link" href="../../03/Linux-data-analysis-tools/">Linux数据处理命令工具</a></li><li class="post-list-item"><a class="post-list-link" href="../../../08/21/shell-show-data/">Linux脚本编程——呈现数据</a></li><li class="post-list-item"><a class="post-list-link" href="../../../08/19/working-with-user-input/">Shell脚本之处理用户输入</a></li><li class="post-list-item"><a class="post-list-link" href="../../../08/11/structural-command-of-shell/">Linux结构化命令</a></li><li class="post-list-item"><a class="post-list-link" href="../../../08/11/basic-shell/">构建基本shell脚本</a></li></ul>




    <script>
        
    </script>
</div>
      <footer id="footer">
    <div class="outer">
        <div id="footer-info">
            <div class="footer-left">
                <i class="fa fa-copyright"></i> 
                2017-2018 王诗翔
            </div>
            <div class="footer-right">
                <a href="http://hexo.io/" target="_blank" title="快速、简洁且高效的博客框架">Hexo</a>  Theme <a href="https://github.com/MOxFIVE/hexo-theme-yelee" target="_blank" title="简而不减 Hexo 双栏博客主题  v3.5">Yelee</a> by MOxFIVE <i class="fa fa-heart animated infinite pulse"></i>
            </div>
        </div>
        
            <div class="visit">
                
                    <span id="busuanzi_container_site_pv" style='display:none'>
                        <span id="site-visit" title="本站到访数"><i class="fa fa-user" aria-hidden="true"></i><span id="busuanzi_value_site_uv"></span>
                        </span>
                    </span>
                
                
                    <span>| </span>
                
                
                    <span id="busuanzi_container_page_pv" style='display:none'>
                        <span id="page-visit"  title="本页阅读量"><i class="fa fa-eye animated infinite pulse" aria-hidden="true"></i><span id="busuanzi_value_page_pv"></span>
                        </span>
                    </span>
                
            </div>
        
    </div>
</footer>
    </div>
    
    <script src="../../../../js/GithubRepoWidget.js"></script>

<script data-main="/js/main.js" src="//cdn.bootcss.com/require.js/2.2.0/require.min.js"></script>

    <script>
        $(document).ready(function() {
            var iPad = window.navigator.userAgent.indexOf('iPad');
            if (iPad > -1 || $(".left-col").css("display") === "none") {
                var bgColorList = ["#9db3f4", "#414141", "#e5a859", "#f5dfc6", "#c084a0", "#847e72", "#cd8390", "#996731"];
                var bgColor = Math.ceil(Math.random() * (bgColorList.length - 1));
                $("body").css({"background-color": bgColorList[bgColor], "background-size": "cover"});
            }
            else {
                var backgroundnum = 2;
                var backgroundimg = "url(/background/bg-x.jpg)".replace(/x/gi, Math.ceil(Math.random() * backgroundnum));
                $("body").css({"background": backgroundimg, "background-attachment": "fixed", "background-size": "cover"});
            }
        })
    </script>





    <script type="text/x-mathjax-config">
MathJax.Hub.Config({
    tex2jax: {
        inlineMath: [ ['$','$'], ["\\(","\\)"]  ],
        processEscapes: true,
        skipTags: ['script', 'noscript', 'style', 'textarea', 'pre', 'code']
    }
});

MathJax.Hub.Queue(function() {
    var all = MathJax.Hub.getAllJax(), i;
    for(i=0; i < all.length; i += 1) {
        all[i].SourceElement().parentNode.className += ' has-jax';                 
    }       
});
</script>

<script src="//cdn.bootcss.com/mathjax/2.6.1/MathJax.js?config=TeX-AMS-MML_HTMLorMML">
</script>


<div class="scroll" id="scroll">
    <a href="#" title="返回顶部"><i class="fa fa-arrow-up"></i></a>
    <a href="#comments" onclick="load$hide();" title="查看评论"><i class="fa fa-comments-o"></i></a>
    <a href="#footer" title="转到底部"><i class="fa fa-arrow-down"></i></a>
</div>
<script>
    // Open in New Window
    
        var oOpenInNew = {
             github: ".github-widget a", 
            
             post: ".article-entry a[href], .copyright a[href]", 
            
            
            
             archives: ".archive-article-title", 
             miniArchives: "a.post-list-link", 
            
             friends: "#js-friends a", 
             socail: ".social a" 
        }
        for (var x in oOpenInNew) {
            $(oOpenInNew[x]).attr("target", "_blank");
        }
    
</script>

    <script>
        var originTitle = document.title;
        var titleTime;
        document.addEventListener("visibilitychange", function() {
            if (document.hidden) {
                document.title = "(つェ⊂) 我藏好了哦~ " + originTitle;
                clearTimeout(titleTime);
            }
            else {
                document.title = "(*´∇｀*) 被你发现啦~ " + originTitle;
                titleTime = setTimeout(function() {
                    document.title = originTitle;
                }, 2000);
            }
        })
    </script>

<script async src="https://dn-lbstatics.qbox.me/busuanzi/2.3/busuanzi.pure.mini.js">
</script>
  </div>
</body>
</html>